const express = require("express");
const blogService = require("../service/blogService");
const blogRouter = express.Router();
const formatResponse = require("../utils/responseFormat");
//添加文章
blogRouter.post("/", async (req, res, next) => {
  const blogInfo = req.body;
  const data = await blogService.addBlog(blogInfo);
  res.send(formatResponse(0, "", data));
});

//删除文章
blogRouter.delete("/:id", async (req, res, next) => {
  const id = req.params.id;
  const data = await blogService.deleteBlog(id);
  res.send(formatResponse(0, "", data));
});

//修改文章
blogRouter.put("/:id", async (req, res, next) => {
  const id = req.params.id;
  const data = await blogService.updateBlog(id, req.body);
  res.send(formatResponse(0, "", data));
});

//获取一个文章
blogRouter.get("/:id", async (req, res, next) => {
  const id = req.params.id;
  const headers = req.headers.authorization;
  const data = await blogService.getBlog(id, headers);
  res.send(formatResponse(0, "", data));
});

//分页获取文章
blogRouter.get("/", async (req, res, next) => {
  const page = +req.query.page || 1;
  const limit = +req.query.limit || 10;
  const keyword = req.query.keyword || "";
  const categoryId = +req.query.categoryId || 0;

  const data = await blogService.getBlogList(page, limit, keyword, categoryId);

  res.send(formatResponse(0, "", data));
});

module.exports = blogRouter;
